<template>
  <div style="position: relative;border-radius:5px;width: 380px;display: flex;justify-content: space-between;">
    <div style="width: 49%;">

    <el-upload  class="upload-demo1" action="#" v-bind="props" v-model:file-list="value" drag  :multiple="false"
                list-type="picture" :http-request="frontend_aliyun_upload_resource"
                :accept="props.upload_type" :limit="1"  :on-success="onSuccess"  :before-upload="beforeUpload"   :on-error="onError"
                :on-exceed="handleExceed" :on-remove="onRemove">

      <div class="color">电脑上传</div>
      <img src="https://www.caixue8.cn/uploads/file.png" class="pos-image" />
      <div class="el-upload__text">
        {{props.title}}
      </div>
    </el-upload>
    <el-progress
        v-show="showProgress"
        :text-inside="true"
        :stroke-width="10"
        :percentage="progress"
    ></el-progress>
  </div>
    <div :class="props.isMemberUse?'shouji1':'shouji'" @click="saomasj('transcription_up')" style="height:102px;display: flex;justify-items: center;align-items: center;justify-content: center;">
      <div>
        <div style="height: 20px;" class="color">手机上传</div>
        <div class="img-d" style="margin-top: 6px">
          <img src="@/assets/images/qrcode.png" class="pos-image">
        </div>
      </div>
    </div>
  </div>

  <el-dialog
      v-model="dialogVisibleVip"
      center
      title="扫描二维码，在手机快速上传"
      width="500"
      :before-close="handleClose"
  >

    <div style=" display: flex;justify-content: center;">
      <img :src="qrcode_url" alt="Base64 Image"/>
    </div>
    <div style="text-align: center;color: red">建议使用微信扫码</div>
    <div @click="handleClose" class="success">已上传完成</div>
  </el-dialog>
</template>

<script setup lang="ts">
import {client , getFileNameUUID} from "~/js/aliyun_utils"
import {ElMessageBox, InputProps} from 'element-plus'
import {
  analysisParaformer,
  getChatCategoryLists,
  getScanFile,
  scanUploadFile,
  scanUploadQrcode,
  videoUnderstand
} from '@/api/chat'
import {useUserStore} from "~/stores/user";
import {computed,ref} from "vue";
import {getVersion} from "~/utils/env";
import feedback from "~/utils/feedback";
const router = useRouter()
const userStore = useUserStore()
interface Props extends Partial<InputProps> {}
const props = withDefaults(defineProps<Props>(), {
  showWordLimit: true,
  isEnable:true,
  isMemberUse:false
})
const dialogVisibleVip = ref(false)

const qrcode_url = ref('')

const saData = ref([])

const handleClose = () => {
  stopPolling();
  dialogVisibleVip.value = false
}

const saomasj = async (key) => {
  if(userStore.userInfo.balance < 100 || !userStore.userInfo.balance){
    await ElMessageBox.confirm(
        'T币必须大于100才能使用解析功能',
        '过期提示',
        {
          confirmButtonText: '去开通',
          cancelButtonText: '暂不开通',
          type: 'warning',
        }
    )
        .then(() => {
          router.push('/openvip');
        })
        .catch(() => {

        })
    return false;
  }
  lx_num.value = 1
  let other_id = window.localStorage.getItem('other_id')
  const data = await scanUploadQrcode({key: key,model_id:other_id })
  if(data){
    dialogVisibleVip.value = true
    qrcode_url.value = data.base64ImageHTML
    saData.value = data
    startPolling()
  }else{
    feedback.msgError(data.msg)
  }
}

const startPolling = () => {
  // 设置轮询间隔时间，例如5秒
  const interval = 1000;
  // 使用setInterval发起请求
  arocde_data.setIntervalFlag = setInterval(() => {
    lunxun()
  }, interval);
}

const arocde_data = reactive({
  setIntervalFlag: null
})

const stopPolling = () => {
  // 清除定时器
  if (arocde_data.setIntervalFlag) {
    clearInterval(arocde_data.setIntervalFlag);
    arocde_data.setIntervalFlag = null;
  }
}

const successWa = () => {
    stopPolling();
    handleClose()
}



const lx_num = ref(0)
const lunxun = async() => {
  lx_num.value++
  console.log(lx_num.value)
  const data = await getScanFile({scan_key: saData.value.tokens})
  if(data.data.length > 0) {
    stopPolling();
    feedback.msgSuccess('上传成功')
    let url =  data.data[0].uri
    value.value = data.data
    emit('videomp3Status', url)
  }else{
    if(lx_num.value >= 20){
      dialogVisibleVip.value = false
      if(data.scan_status == 0){
        feedback.msgError('二维码已过期')
        stopPolling();
      }
    }else{
      if(data.scan_status == 1){
        lx_num.value = 21
        feedback.msgSuccess('扫码成功')
        dialogVisibleVip.value = false
      }
    }
  }
}





const showProgress = ref(false)
const progress = ref(0)
const fileurlsname = ref('')
const videl_file = ref([])
const emit = defineEmits<{
  (event: 'update:modelValue', value: any): void
}>()
const value = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})
const img_type = ref([])
if(props.upload_type){
  img_type.value = props.upload_type.split(',')
}
const headers = computed(() => ({
  token: userStore.token,
  version: getVersion()
}))
const data = computed(() => ({
  type: 'paraformer'
}))


const frontend_aliyun_upload_resource = (file) => {
  const that = this;
  async function multipartUpload() {
    let temporary = file.file.name.lastIndexOf(".");
    let fileNameLength = file.file.name.length;
    let fileFormat = file.file.name.substring(
        temporary + 1,
        fileNameLength
    );

    let fileName = getFileNameUUID() + "." + fileFormat;
    var obj = createFolderUrl() + fileName
    client().multipartUpload(obj, file.file, {
      progress: function(p) {
        //p进度条的值
        console.log(p);
        showProgress.value = true;
        progress.value = Math.floor(p * 100);
      }
    })
        .then(result => {
          console.log(result)
          //上传成功返回值，可针对项目需求写其他逻辑
          let url = "https://oos.teacherai.cc/" + result.name
          //存入file_list中
          //调用文件解析接口
          getVideo(url,result.name)
        })
        .catch(err => {
          console.log("err:", err);
        });
  }
  multipartUpload();
}

const getVideo = async (url,file_path) => {
 let data =  await analysisParaformer({ file_urls: url,file_urls_name:fileurlsname.value,file_path:file_path })
  showProgress.value = false

  emit('videomp3Status', data.transcription_url)
}

//创建文件夹路径
const createFolderUrl = (e) => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const directory = 'sm-frontend/' + year + '/' + month + '/';
  return directory;
}

const onSuccess = async (e) => {
  if(e.code == 0){
    ElMessage({
      showClose: true,
      message: e.msg,
      type: 'error',
    })
    if (value.value && value.value.length > 0) {
      console.log('Filtering files...')
      value.value = value.value.filter(file => {
        console.log('File object:', file)
        console.log('File response:', file.response)
        return file.response.code !== 0
      })
    }
    emit('videomp3Status', 1)
  }else{
    console.log(value.value[0].response)
    let url = value.value[0].response.data.uri
    //调用文件解析接口
    console.log('执行了吗',url)
    const data = await analysisParaformer({ file_urls: url,file_urls_name:fileurlsname.value,file_path:file_path })
    emit('videomp3Status', data.transcription_url)
  }
}
const onProgress = () => {

}


const onRemove = async (file, fileList) => {

}

const handleExceed = () => {
  ElMessage({
    showClose: true,
    message: '上传的文件数量不能超过 ' + props.maxlength + '个',
    type: 'error',
  })
}



const beforeUpload = async (file) => {

  if(userStore.userInfo.balance < 100 || !userStore.userInfo.balance){
    await ElMessageBox.confirm(
        'T币必须大于100才能使用解析功能',
        '过期提示',
        {
          confirmButtonText: '去开通',
          cancelButtonText: '暂不开通',
          type: 'warning',
        }
    )
        .then(() => {
          router.push('/openvip');
        })
        .catch(() => {

        })
   return false;
  }else {


    fileurlsname.value = file.name

    const isLt500KB = file.size / 1024 / 1024 < props.maxupload;
    if (!isLt500KB) {
      ElMessage({
        showClose: true,
        message: '上传的文件大小不能超过 ' + props.maxupload + 'M',
        type: 'error',
      })
    }

    try {
      await ElMessageBox.confirm(
          '解析音视频需要扣除金币',
          '扣除金币提示',
          {
            showClose: false,
            confirmButtonText: '继续',
            cancelButtonText: '关闭'
          });
      emit('videomp3Status', 0)
      return isLt500KB;
    } catch (e) {
      return false;
    }
  }
}
const onError = (e) => {
  console.log(e)
  ElMessage({
    showClose: true,
    message: e.msg,
    type: 'error',
  })
  emit('videomp3Status', 1)
}

const onChange = (e) => {

  console.log(e)
}

</script>
<style lang="scss" scoped>
.pos-image {
  width: 40px!important;
  height: 40px!important;
  left:0;
  right: 0;
  text-align: center;
  margin: auto;
  top:50%
}
.upload-demo1{
  :deep(.el-upload-dragger) {
    border:0.5px solid #784c2c;
    padding: 10px;
  }
}
.upload-demo{
  :deep(.el-upload-dragger) {
    padding: 10px;
  }
}
.shouji {
  width: 50%;
  line-height: 22px;
  text-align: center;
  height: 60px;
  border: 1px dashed #dcdfe6;
}
.shouji1 {
  width: 50%;
  line-height: 22px;
  text-align: center;
  height: 62px;
  border: 1px solid #784c2c;
  border-radius: 5px;
}
.img-d {
  text-align: center;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.success {
  text-align: center;
  background: #ffb100;
  color: white;
  border-radius: 40px;
  cursor: pointer;
}
.color {
  color: #9e9e9e;
}
</style>
